'use strict';

import React, { Component } from 'react';

import {
  StyleSheet,
  View,
  Text,
} from 'react-native';

import {NavigationBar} from 'react-native-navigator'

import fs, {Uint8ArrayFromHex, HexFromUint8Array} from 'react-native-fs'
import crypto from 'crypto-js'

console.log(fs.HOME)

class FileComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {};

    this.test();
  }

  appMsg(msg) {
    this._msg = `${this._msg || ''}\n${msg}`;
    this.setState({text: this._msg});
  }
  async test() {
    this.appMsg(await fs.readir(fs.HOME, true))

    const index = await fs.HOME+'/Documents/index.js';
    
    const hex = crypto.enc.Utf8.parse('我是中国人').toString(crypto.enc.Hex);
    let buffer = Uint8ArrayFromHex(hex);

    this.appMsg('writeFile: '+ crypto.lib.WordArray.create(buffer).toString(crypto.enc.Utf8));
    await fs.writeFile(index, buffer);
    const file = await fs.open(index);
    buffer = await file.read();
    console.log(HexFromUint8Array(buffer));
    this.appMsg('read ' + TypedArrayToUtf8(buffer));
  }

  render() {
    return (
      <View style={styles.container}>
        <NavigationBar navigator={this.props.navigator} title='File'/>
        <Text>{this.state.text}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#F5FCFF'
  }
});

function TypedArrayToUtf8(array) {
  return crypto.lib.WordArray.create(array).toString(crypto.enc.Utf8);
}

export default FileComponent;